/**
 * 
 */
package baidu;

import java.io.FileNotFoundException;
import java.sql.Date;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Map;
import java.util.UUID;


import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import com.wixc.entity.NewBean;
import com.wixc.util.ConstantsUtil;
import com.wixc.util.ImageUtil;
import com.wixc.util.JdbcUtils;
import com.wixc.util.LoginUtil;

/**
 * @author weichuanxi
 * @date 2016骞�鏈�3鏃�13:23:00
 */
public class BaiduCircleAreaNews {
	static ArrayList<NewBean> list = new ArrayList<NewBean>();

	
	static String path2 = "style" + ConstantsUtil.split + "indexIamges" + ConstantsUtil.split;

	public static void main(String[] args) throws FileNotFoundException, SQLException {
		ImageUtil.delAllFile(ConstantsUtil.path + path2);

		Baidu_HotNews_Run();
		Connection con = JdbcUtils.getConnection();
		Statement state = (Statement) con.createStatement();
		try {
			JdbcUtils.saveNews(list, "insert into hotnews (id, title, detail, source, imageUrl,typeid,insertTime) values (?,?, ?,?,?,?, ?)");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		state.execute("delete from hotnews where id not in(select * from (select max(id) from hotnews group by title) as tmp)");
		con.close();
	}

	public static void Baidu_HotNews_Run() {
		LoginUtil util = new LoginUtil();
		String html = util.Get("http://news.baidu.com/");
		try {
			processor(util, html);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	
	}

	private static ArrayList<NewBean> processor(LoginUtil util, String html) throws FileNotFoundException, SQLException {

		return deal(util, html, ConstantsUtil.hotNews);
	}

	@SuppressWarnings("deprecation")
	private static ArrayList<NewBean> deal(LoginUtil util, String html, int typeid) throws SQLException {

		String datas = html.substring(html.indexOf("cpOptions_1.data.push"), html.lastIndexOf("imgList.push"));
		String[] data = datas.split("imgList.push");
		for (int i = 0; i < data.length; i++) {
			String string = data[i];
			String temp = string.substring(string.indexOf("push(") + 5, string.length()).replace("\"title\": \"\",", "").replace("//", "")
					.replace(");", "");
			Map<String, Object> map = LoginUtil.json2Map(temp);
			String title = map.get("title") + "";
			String url = map.get("url") + "";
			String imgUrl = map.get("imgUrl") + "";
			 String imgname = (UUID.randomUUID() + ".jpg").replace("-", "");
			try {
				ImageUtil.download(imgUrl, ConstantsUtil.path + path2 + imgname);
			} catch (Exception e) {
				e.printStackTrace();
			}
			NewBean news = new NewBean(0, title, url, imgUrl, path2 + imgname, typeid, new Date(System.currentTimeMillis()));
			list.add(news);
		}
		return list;
	}
}
